﻿module Sustainalytics.GovernanceReports {

    export class AlertAddController {

        //private currentAlert: GovernanceAlertDto;
        private governanceService: GovernanceService;
        private selectedFile: any;
        private oldFileName: string;
        private newFileName: string;
        //disable save button until the pdf/image upload
        public isSaveDisabled: boolean;

        constructor(
            private $scope: ICompanyControllerScope,
            private $modal: IModal,
            private $modalInstance: IModalInstance,
            private notificationFactory: INotificationFactory,
            private staticObjects: IStaticObjects,
            private $routeParams: ng.route.IRouteParamsService,
            private currentAlert: GovernanceAlertDto,
            private companyProfile: GovernanceProfileDto,
            private companyName: string,
            GovernanceService) {

            var ctx = this;
            $scope['alertCompany'] = ctx;
            ctx.governanceService = GovernanceService;
            if (ctx.currentAlert == null) {
                ctx.currentAlert = new GovernanceAlertDto();
                ctx.currentAlert.publicationDate = new Date();
            }
            if (ctx.currentAlert != null && ctx.currentAlert.fileName != null) {
                ctx.oldFileName = ctx.currentAlert.fileName.toString();
            }
            ctx.isSaveDisabled = false;
        }

        public cancel = function () {
            var ctx = this;
            ctx.$modalInstance.close({ companyProfile: ctx.companyProfile });
        };

        private showErrorCode(code: number) {
            var ctx = this;
            var msg = ctx.staticObjects.getMessageByInternalCode(code);
            ctx.notificationFactory.error('', msg);
        }

        // report upload
        public onSelectPdf(files, alert): any {
            var ctx = this;
            ctx.isSaveDisabled = true;
            ctx.currentAlert = alert;
            var file = files[0]; // html assures is just 1
            if (file) {
                if (file.size > 10 * 1024 * 1024 || file.type != "application/pdf") {
                    ctx.showErrorCode(2108);
                    ctx.isSaveDisabled = false;
                }
                else {
                    ctx.selectedFile = file;
                    var promise = ctx.governanceService.fileUpload(ctx.selectedFile, ctx.currentAlert.fileId);
                    promise.then(
                        //success
                        (data: { id: string; fileUrl: string; filename: string }) => {
                            ctx.$scope.$evalAsync(() => {
                                ctx.currentAlert.fileId = data.id;
                                ctx.currentAlert.fileUrl = data.fileUrl;
                                ctx.newFileName = data.filename;
                                ctx.currentAlert.fileName = null;
                                ctx.notificationFactory.success('Upload succeeded.');
                                ctx.isSaveDisabled = false;
                            });
                        },
                        //error
                        () => {
                            ctx.showErrorCode(2114);
                            ctx.currentAlert.fileName = ctx.oldFileName;
                            ctx.isSaveDisabled = false;
                        }
                        );
                }
            }
        }

        public saveAlert(alert: GovernanceAlertDto) {
            var ctx = this;
            var addAlert = true;

            var message = ctx.validateAlert(alert);

            if (message == "") {
                // search alert
                if (ctx.companyProfile.alerts != null) {
                    for (var i = 0; i < ctx.companyProfile.alerts.length; i++) {
                        if (ctx.companyProfile.alerts[i].id == alert.id) {
                            ctx.companyProfile.alerts[i] = alert;
                            ctx.companyProfile.alerts[i].fileName = ctx.newFileName;
                            addAlert = false;
                        }
                    }
                } else {
                    ctx.companyProfile.alerts = new Array<GovernanceAlertDto>();
                }

                if (addAlert) {
                    alert.fileName = ctx.newFileName;
                    ctx.companyProfile.alerts.push(alert);
                }

                // save alert
                var saveAlertPromise: ng.IPromise<GovernanceProfileDto> = ctx.governanceService.saveProfile(ctx.companyProfile);

                saveAlertPromise.then(function (corpData) {
                    ctx.companyProfile = corpData['data'];
                });

                saveAlertPromise.finally(function () {
                    ctx.cancel();
                    ctx.notificationFactory.success("Save operation executed successfully.");
                });
            }
            else {
                ctx.notificationFactory.error('', message);
            }
        }

        private validateAlert(alert: GovernanceAlertDto) {
            var ctx = this;

            var message = "";
            if (alert == null) {
                message += "Please check the following field(s): " + "<br/> Publication date" + "<br/> Title";
                if (ctx.selectedFile == null )
                    message += "<br/> Pdf file";
            }
            else if (alert.publicationDate == null ||
                alert.title == null ||
                (ctx.selectedFile == null && alert.fileId == null)) {
                message += "Please check the following field(s): ";

                if (alert == null || alert.publicationDate == null)
                    message += "<br/> Publication date";
                if (alert == null || alert.title == null)
                    message += "<br/> Title";
                if (ctx.selectedFile == null && alert.fileId == null)
                    message += "<br/> Pdf file";
            }
            else {
                if (alert.title.length > 100) {
                    message += "The title should have maximum 100 characters."
                }
            }
            return message;
        }

    }

    export var alertAddControllerName = 'AlertAddController';

    angular.module(governanceReportsModuleName).controller(alertAddControllerName, AlertAddController);
}